package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.user.UserConstants.AdminConstans;
import com.heima.common.exception.CustomException;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.feign.ApAuthorFeign;
import com.heima.user.feign.WmUserFeign;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.IdCardUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional

public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>  implements ApUserRealnameService {
    @Autowired
    private ApUserMapper apUserMapper;
    @Autowired
    private ApAuthorFeign apAuthorFeign;
    @Autowired
    private WmUserFeign wmUserFeign;

    @Override
    public ResponseResult findListByStatus(AuthDto authDto) {
        if (authDto==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        authDto.checkParam();
        Page page = new Page(authDto.getPage(),authDto.getSize());
        LambdaQueryWrapper<ApUserRealname> queryWrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus()!=null){
             queryWrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getStatus, authDto.getStatus());
        }
        IPage iPage = page(page, queryWrapper);
        PageResponseResult result = new PageResponseResult(authDto.getPage(), authDto.getSize(), (int) iPage.getTotal());
        result.setData(iPage.getRecords());
        return result;
    }

    //用户认证通过后修改认证状态、创建自媒体账号及作者账号
    @Override
    @GlobalTransactional
    public ResponseResult updateStatusById(AuthDto dto) {
        if (dto==null || dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (statusCheck(dto.getStatus())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"状态参数非法");
        }
        ApUserRealname apUserRealname = new ApUserRealname();
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(dto.getStatus());
        if (StringUtils.isNotBlank(dto.getMsg())){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        if (dto.getStatus().equals(AdminConstans.PASS_AUTH)){
            createWmUserAndAuthor(dto.getId());
        }

      //  System.out.println(1/0);
        return ResponseResult.okResult();
    }

    private void createWmUserAndAuthor(Integer id) {
        ApUserRealname apUserRealname = getById(id);

        /*boolean b = IdCardUtils.checkIdCardInfo(apUserRealname.getRealName(), apUserRealname.getIdno());
        if (!b){
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户身份证信息错误"));
        }*/

        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser==null)
            throw new CustomException(ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实名认证关联用户不存在"));
        WmUser wmUser = wmUserFeign.findByName(apUserRealname.getName());
        if (wmUser==null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setStatus(9);
            wmUser.setImage(apUser.getImage());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUserFeign.save(wmUser);
        }
        createAuthor(wmUser);

    }

    private void createAuthor(WmUser wmUser) {
        Integer i = wmUser.getApUserId();
        ApAuthor apAuthor = apAuthorFeign.findByUserId(i);
        if (apAuthor==null){
            apAuthor = new ApAuthor();
            apAuthor.setName(wmUser.getName());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setCreatedTime(new Date());
            apAuthor.setType(2);
            apAuthorFeign.save(apAuthor);
        }
    }

    private boolean statusCheck(Short status){
        if (status == null || ( !status.equals(AdminConstans.FAIL_AUTH) && !status.equals(AdminConstans.PASS_AUTH))) {
            return true;
        }
        return false;
    }
    }

